package com.youjiang.spirder.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.rtf.RtfWriter2;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @Description: 导出word
 * @Company: yimo
 * @author: Kwum
 * @date 2018年2月24日 下午6:02:30
 */

public class WordUtils {
	
	public static final String UC_CONTENT_CAPTCHA = "var xissJsonData = (.*?);";
	public static final String TENCENT_CONTENT_CAPTCHA = "<script>window.__initData = (.*?);</script>";
	public static final String P_TAG_CAPTCHA = "<p>(.*?)</p>";
	
	public static void main(String[] args) throws IOException {
		String url = "http://m.uczzd.cn/ucnews/news?app=ucnews-iflow&aid=11498663589260882609&cid=408250330&zzd_from=ucnews-iflow&uc_param_str=dndsfrvesvntnwpfgibi&recoid=17498584817348621597&rd_type=reco";
		spirdeUCTouTiaoInfoByUrl(url);
	}
	
	/**
	 * 通过URL获取UC头条文章详情
	 * @param articleUrl 文章URL
	 * @throws IOException
	 * @author Kwum
	 * @throws InterruptedException 
	 */
	public static JSONArray spirdeUCTouTiaoInfoByUrl(String articleUrl) throws IOException {
		JSONArray result = new JSONArray();
		
		//通过jsoup获取内容
		Document document = Jsoup.connect(articleUrl)
							.ignoreContentType(true)
							.get();
		JSONObject contentJson = null;
		
		//用正则表达式过滤内容json
		Pattern p = Pattern.compile(UC_CONTENT_CAPTCHA);
		
        Matcher macher = p.matcher(document.body().toString());
        while (macher.find()) {
        	contentJson = JSONObject.fromObject(macher.group(1));
            break;
        }
        
        //获取内容
        String content = contentJson.optString("content", "");
        
        if(!StringUtils.equalsIgnoreCase("", content)) {
        	//将图片分别插入内容当中
    		JSONArray imgArray = contentJson.getJSONArray("images");
    		for(int i = 0; i < imgArray.size(); i++) {
    			JSONObject imgJson = imgArray.getJSONObject(i);
//    			String imgDesc = imgJson.optString("description", "");
    			String imgUrl = imgJson.optString("url", "");
    			
    			content = content.replace("<!--{img:" + i + "}-->", "<p><img>" + imgUrl + "</p>");
    		}
    		
    		//通过p标签查找内容
    		p = Pattern.compile(P_TAG_CAPTCHA);
            macher = p.matcher(content);
            while (macher.find()) {
            	JSONObject json = new JSONObject();
            	String con = macher.group(1);
            	if(StringUtils.startsWithIgnoreCase(con, "<img>")) {
    				
    				//图片
    				json.put("img", con.substring(5));
    			}else if(StringUtils.startsWithIgnoreCase(con, "<strong>")) {
    				
    				//粗体
    				json.put("bold", con.substring(8, con.length()-9));
    			}else {
    				
    				//正常字体
    				json.put("normal", con);
    			}
    			
    			//放进结果集
    			result.add(json);
            }
        }
        return result;
	}
	
	/**
	 * 通过URL获取腾讯新闻文章详情
	 * @param articleUrl 文章URL
	 * @throws IOException
	 * @author Kwum
	 */
	public static JSONArray spirdeTencentNewInfoByUrl(String articleUrl) throws IOException {
		
		JSONArray result = new JSONArray();
		
		//通过jsoup获取内容
		Document document = Jsoup.connect(articleUrl)
							.ignoreContentType(true)
							.get();
		JSONObject contentJson = null;
		
		//用正则表达式过滤内容json
		Pattern p = Pattern.compile(TENCENT_CONTENT_CAPTCHA);
        Matcher macher = p.matcher(document.body().toString());
        while (macher.find()) {
        	contentJson = JSONObject.fromObject(macher.group(1));
            break;
        }
        
		//处理内容
		JSONArray imgArray = contentJson.getJSONObject("content").getJSONArray("content");
		for(int i = 0; i < imgArray.size(); i++) {
			JSONObject imgJson = imgArray.getJSONObject(i);
			String imgUrl = imgJson.optString("img_url", "");
			String desc = imgJson.optString("desc", "");
			
			JSONObject json = new JSONObject();
			if(!StringUtils.equalsIgnoreCase("", imgUrl)) {
				
				//图片
				json.put("img", imgUrl);
			}else if(!StringUtils.equalsIgnoreCase("", desc)) {
				
				//粗体
				if(StringUtils.startsWithIgnoreCase(desc, "<strong>")) {
					json.put("bold", desc.substring(8, desc.length()-9));
				}else {
					//正常字体
					json.put("normal", desc);
				}
			}
			
			//放进结果集
			result.add(json);
		}
		return result;
	}
	
	/**
	 * 通过URL获取天天快报文章详情
	 * @param articleUrl 文章URL
	 * @throws IOException
	 * @author Kwum
	 */
	public static JSONArray spirdeKuaiBaoNewInfoByUrl(String articleUrl) throws IOException {
		JSONArray result = new JSONArray();
		
		//通过jsoup获取内容
		Document document = Jsoup.connect(articleUrl)
							.ignoreContentType(true)
							.get();
		
		//获取p标签内容
		Elements elements = document.getElementsByTag("p");
		
		//处理内容
		for(Element e : elements) {
			JSONObject json = new JSONObject();
			if(StringUtils.startsWith(e.html(), "<img src")) {
				
				//图片
				json.put("img", e.html().substring(10, e.html().length()-38));
			}else if(StringUtils.startsWith(e.html(), "<strong><img src")) {
				
				//图片
				json.put("img", e.html().substring(18, e.html().length()-47));
			}else if(StringUtils.startsWith(e.html(), "<strong>")) {
				
				//粗体字体
				json.put("bold", e.html().substring(8, e.html().length()-9));
			}else if(StringUtils.startsWith(e.html(), "正在加载...")) {
			}else if(StringUtils.equals(e.html(), "")) {
			}else{
				
				//正常字体
				json.put("normal", e.html());
			}
			
			//放进结果集
			result.add(json);
		}
		return result;
	}
	
	/***
	 * 
	 * Description:把文档导出到客户端
	 * 
	 * @author feng
	 * @date 2017年10月31日 下午5:21:07
	 * @version 1.0
	 * @param response
	 * @param workbook
	 * @param fileName
	 *            文件名，不需要后缀
	 * @throws Exception
	 */
	public static void exportClient(HttpServletResponse response, String fileName, JSONArray jsonArray)
			throws Exception {
		// 通过Response把数据以Excel格式保存
		response.reset();
		// 设置response流信息的头类型，MIME码
		response.setContentType("application/msexcel;charset=UTF-8");
		response.addHeader("Content-Disposition",
				"attachment;filename=\"" + new String((fileName + ".doc").getBytes("UTF-8"), "ISO8859_1") + "\"");
		// 创建输出流对象
		OutputStream out = response.getOutputStream();
		
		// 将创建的Excel对象利用二进制流的形式强制输出到客户端去
		/** 创建Document对象(word文档) **/  
        Rectangle rectPageSize = new Rectangle(PageSize.A4);  
        rectPageSize = rectPageSize.rotate();  
          
        // 创建word文档,并设置纸张的大小  
        com.lowagie.text.Document doc = new com.lowagie.text.Document(PageSize.A4);  
          
        //建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中 
        RtfWriter2.getInstance(doc, out);  
        doc.open();  
        
        //粗体字
        Font boldFont = new Font();
        boldFont.setStyle(Font.BOLD);
        boldFont.setSize(16);
        
        //普通字体
        Font normalFont = new Font();
        boldFont.setSize(16);
        Paragraph p;
        
        for(int i = 0; i < jsonArray.size(); i++) {
        	JSONObject json = jsonArray.getJSONObject(i);
        	
        	//图片
        	String img = json.optString("img", "");
        	//粗体字
        	String bold = json.optString("bold", "");
        	//正常字体
        	String normal = json.optString("normal", "");
        	
        	//往doc里面插入内容
        	if(!StringUtils.equalsIgnoreCase("", img)) {
        		Image png = Image.getInstance(img);
                doc.add(png);
        	}else if (!StringUtils.equalsIgnoreCase("", bold)) {
        		p = new Paragraph(bold);
                p.setFont(boldFont);
                doc.add(p);
        	}else if (!StringUtils.equalsIgnoreCase("", normal)) {
        		p = new Paragraph(normal); 
                p.setFont(normalFont);
                doc.add(p);
        	}
        }
        doc.close();  
		// 强制将数据从内存中保存
		out.flush();
		out.close();
	}
}
